//购物车数组
let shopList =[]
function buy(bookId) {
   $('shopDiv').style.visibility="visible"
  $('shopDiv').style.width = document.documentElement.clientWidth+"px"
  $('shopDiv').style.height = document.documentElement.clientHeight+"px"

  //根据商品id得到商品
  let bookObj = shopList.find(n => n.book.code==bookId)
   if(bookObj == null){//说明购物车不存在该商品
     //从商品数组中查询该商品
      bookObj = booksArray.find(n =>n.code ==bookId)
     //创建购物车对象
     var  shopObj = {book:bookObj,num:1}
     //在购物车添加商品
     shopList.push(shopObj)
   }
   else {//购物车有该商品，数量加一
     bookObj.num ++
   }
  showShopInfo()
}

/***
 *
 */
function showShopInfo() {
        let str =""
  let total =0
        shopList.forEach(n =>{
          str +=`<tr><td>${n.book.name}</td><td>${n.book.price}</td><td><input type="number" value="${n.num}" onblur="changNumber(this,${n.book.code})"></td>
         <td>${n.book.price * n.num}</td><td><input type="button" value="移除商品" onclick="removeBook(${n.book.code})"></td></tr>`
          total +=n.book.price * n.num
        })
        $("shopDate").innerHTML = str
        $("totalSpan").innerHTML = total
}

/***
 * 移除购物车商品
 * @param bookId 书籍id
 */
function removeBook(bookId) {
  //查找商品在购物车中的下标
   let index =  shopList.findIndex(n =>n.book.code ==bookId)
   shopList.splice(index,1)
   showShopInfo()
}

/***
 *
 * @param txtObj
 * @param bookId
 */
function changNumber(txtObj,bookId) {
    if(txtObj.value.length ==0 || txtObj.value<1){
        txtObj.value =1
    }
    //根据书籍id找到购物车对象
     let shopObj = shopList.find(n => n.book.code == bookId)
  //修改数量
    shopObj.num = parseInt(txtObj.value)
    showShopInfo()
}
